$(document).ready(function() {

    init();	// init() is defined @ js/init.js

    $('#div-j').buildManager({sectionType:'J'});
    $('#div-q').buildManager({sectionType:'Q'});
    
    $('#hrefwhatsthis').overlay();

});	// end of onLoad

function keygen(type, k)
{
    var key = type + k;
    return key;
}

var j_database = jQuery.extend(true, {}, selected_journals); // clone database

function refresh_database(_id) {
    /* link to database file on developer's site */
    var json_url = "http://nus-libproxy-chrome-extension.googlecode.com/files/journals.json" + "?rnd=" + (new Date()).getTime();
//    var json_url = "./journals.json"

    $span = $("<span></span>").load(json_url, function() {
	var jstr = $span.text();
	j_database = JSON.parse(jstr);	// update the j_database;
		
	if(_id===undefined) {}
	else {				// highlight the database update;
	    var HL="Updated";
	    var ver = j_database["Choose a Category..."][0].version;
	    if (ver != undefined) HL += '; ver:' + ver;
	    $highlight=$("<span class='highlight'></span>").html(HL);

	    $(_id).hide().after($highlight);
	    $highlight.fadeIn("fast", function() {
		setTimeout(function() { $highlight.fadeOut("slow"); },900); 
		setTimeout(function() { $highlight.remove(); }, 2000);
		setTimeout(function() { $(_id).show(); }, 1500); 
	    }); 
	}
	
	$('.categorySelectClass').trigger("DatabaseUpdatedEvent"); // send out triggers;
    });
}

(function($){

    $.fn.buildManager = function(customOptions) {
 
	var options = {
	    sectionType: "J",
	};

	$.extend(options, customOptions);

	var Type = options.sectionType;

	var defs = {
	    "J": { num: "num_of_portals",
		   key: "url",
		   description: "URL (<a class='green' target='_blank' href='http://libpweb1.nus.edu.sg/web/appmanager/lib/desk?_nfpb=true&_pageLabel=defaultDesktopLabel_book_11'>list of e-journals</a> subscribed by NUS)"
		 },
	    "Q": { num: "num_of_qs",
		   key: "q",
		   description: "Format for linking to citation (<a class='green' rel='#whatsthis' id='hrefwhatsthis' href='#'>what's this?</a>)"
		 }
	}

	return this.each( function(index) {
	
	    var $div = $(this);
	    var $selectCategory;    // select tag for category
	    var $selectJournal;	    // select tag for journals
	    var $form;		    // Manual Input form
	    var $buttonApply;	    // Apply Changes button
	    var $aRequest;	    // request href
	    var $aUpdate;	    // update href
	    var $buttonInput;	    // Manual Input button

	    var request_url = 'http://spreadsheets.google.com/viewform?hl=en&formkey=dGdyNE5fVHJUUFR3NjlZQ3Z3UHZCOUE6MA';
	    var SID = '';   // section ID = Type + index;

	    function init(){
		while($("#section" + Type + index).size() > 0) index++;
		
		SID = Type + index;

		$selectCategory = $("<select></select>")
				.attr('id', 'sel_Cat_' + SID)
				.addClass('categorySelectClass');

		$selectJournal  = $("<select></select>")
				.attr('id', 'sel_Jn_' + SID)
				.attr('multiple', 'multiple')
				.attr('title', "Click to Select a Journal");

		build_category_Select();

		build_journal_Select();

		build_others();

		$div.append($selectJournal)
		    .append($form)
		    .append($buttonInput)
		    .append($buttonApply)
		    .append($aUpdate)
		    .append($aRequest);

		$selectJournal.asmSelect({
			addItemTarget: 'bottom',
			animate: true,
			highlight: true,
			sortable: true
		    });

		$selectJournal.parent("div").prepend($selectCategory);

		$selectCategory.change( function() {
		    $buttonApply.click();
		    build_journal_Select();
		    $selectJournal.change();
		});

		$(".categorySelectClass")
		.live( "DatabaseUpdatedEvent", function() {
		    build_category_Select();
		    $selectCategory.change();
		});

	    }

	    function build_category_Select(){
		$selectCategory.empty();

		var listOpt = "";
		for(var field in j_database) {
		    listOpt +="<option value=\""+field+"\">"+field+"</option>";
		}

		$selectCategory.html(listOpt);
		$selectCategory.children("option:eq(0)")
			       .attr('disabled','disabled')
			       .attr('selected', 'selected');
	    }

	    function build_journal_Select(){
		$selectJournal.empty();
		var cat = $selectCategory.val();

		var selected_list = load_stored_journal();
		var final_list = merge_with_dabatase(selected_list, cat);

		for(var i in final_list) {
		    var $item = $("<option></option>")
			.attr('rel', final_list[i][defs[Type].key])
			.html(final_list[i].name);

		    $item.attr('selected', final_list[i].selected != undefined);
		    $selectJournal.append($item);
		}

		$selectJournal.attr('disabled', (cat==$selectCategory.children("option:eq(0)").attr('value')) );

    		function load_stored_journal() {
		    var len = Number( getItem(defs[Type].num) );
		    var list = new Array();

		    for(var i = 0; i < len; i++) {
			var obj = getItem(keygen(Type, i)).split('\t');

			list[i] = { name: obj[0], url : obj[1], 
				       q: obj[1], selected:"selected" };
		    }
		    return list;
		}

		function merge_with_dabatase(_selected_list, _cat) {
		    var database_list = new Array();
		    for(var i in j_database[_cat]) {
			if(j_database[_cat][i][defs[Type].key] === undefined) continue;
			database_list.push(j_database[_cat][i]);
		    }

		    if(_selected_list.length == 0) {return database_list;}

		    var unselected_list = new Array();

		    for(var k in database_list) {
		      for(var i in _selected_list) {
			if(_selected_list[i].name == database_list[k].name) {break;}
			if(i==_selected_list.length-1) {
			    unselected_list.push( database_list[k]);
			}
		      }
		    }
		    var _full_list = unselected_list.concat(_selected_list);
		    return _full_list;
		}
	    }

	    function build_others(){
		$aRequest = $("<a class='mgl20 green f90''></a>")
			    .attr('href', request_url).attr('target', '_blank')
			    .html("request for my favorites");

		$aUpdate =  $("<a class='mgl20 green f90' href='#'></a>")
			    .attr('id', 'updateDb' + SID)
			    .html("refresh database")
			    .click(function() {
				    refresh_database('#updateDb' + SID);
			    });

		$buttonInput = $("<button>Manual Input</button>")
			       .click(function() {
				    $form.slideToggle();
			       });

		$buttonApply = $("<button>Apply Changes</button>").click(
		    function(){
			var len =Number(getItem(defs[Type].num));
			for(var i = 0; i < len; i++)  {
			    removeItem( keygen(Type, i) );
			}

			len = 0;
			$('#sel_Jn_'+SID+' option:selected').each(function(n) {
			    var name = $(this).text();
			    var u    = $(this).attr('rel');
			    var key = keygen(Type, len);
			    setItem(key, name +'\t'+ u);
			    len++;
			});
			setItem(defs[Type].num, len);
		    });

		$form = $("<form></form>").addClass('inputForm');

		  var Str = "<td><span class='f80'>Journal</span><br><input class='w160 mgr20'></input></td>";
		  Str += "<td><span class='f80'>";
		  Str += defs[Type].description + "</span><br>";
		  Str += "<input class='w280 mgr20'></input>";
		  Str += "<button type='submit'>Add</button></td>";
		  Str += "<td style='vertical-align:middle'><img class='imgcross' src='images/deletecross.gif'></img></td>";

		$form.html(Str).submit(function(e){
		    var j = $form.find("input:eq(0)").val();
		    var u = $form.find("input:eq(1)").val();
		    var $option = $("<option></option>").text(j)
		        .attr('rel', u).attr("selected", 'selected');

		    $selectJournal.append($option).change();

		    $(this).find("input:eq(0)").val('').focus();
		    $(this).find("input:eq(1)").val('');

		    e.preventDefault();
		});

		$form.find("img").click( function(){
		    $form.slideToggle();
		});

	    }

	    init();

	}); // each()

    }

})(jQuery);
